import base64
import pickle
from django_redis import get_redis_connection


def union_carts(request, user, response):
    """合并购物车"""
    # 获取cookie中的购物车信息
    cookie_cart = request.COOKIES.get('carts', None)
    if not cookie_cart:
        return response
    cookie_cart = pickle.loads(
        base64.b64decode(
            cookie_cart.encode()
        )
    )
    # 获取redis中的购物车信息
    redis_conn = get_redis_connection('carts')
    # 将cookie中的信息合并到redis中
    for sku_id, value in cookie_cart.items():
        # if redis_conn.hexists('carts_{}'.format(user.id), sku_id):  # 存在就覆盖
        redis_conn.hset('carts_{}'.format(user.id), sku_id, value['count'])
        # else:  # 不存在就追加
        #     redis_conn.hmset('carts_{}'.format(user.id), {sku_id: value['count']})
        if value['selected']:
            redis_conn.sadd('selected_{}'.format(user.id), sku_id)
        else:
            redis_conn.srem('selected_{}'.format(user.id), sku_id)

    # 清除cookie中的购物车信息
    response.delete_cookie('carts')

    return response



